package com.lty.jeeg.server.modules.fas.service.impl;

import com.lty.jeeg.server.common.dto.ResponseInfo;
import com.lty.jeeg.server.common.page.table.PageTableHandler;
import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;
import com.lty.jeeg.server.common.utils.BeanConverter;
import com.lty.jeeg.server.modules.fas.dao.GoodsCategoryDao;
import com.lty.jeeg.server.modules.fas.dao.GoodsDao;
import com.lty.jeeg.server.modules.fas.dao.StockDao;
import com.lty.jeeg.server.modules.fas.dto.GoodsCategoryDTO;
import com.lty.jeeg.server.modules.fas.dto.GoodsDTO;
import com.lty.jeeg.server.modules.fas.dto.SurplusLossesDTO;
import com.lty.jeeg.server.modules.fas.model.Stock;
import com.lty.jeeg.server.modules.fas.vo.SurplusLossesVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lty.jeeg.server.modules.fas.dao.SurplusLossesDao;
import com.lty.jeeg.server.modules.fas.model.SurplusLosses;
import com.lty.jeeg.server.modules.fas.service.SurplusLossesService;

import java.util.HashMap;
import java.util.Map;


/**
 * @author : xuchen
 * @date : 2019-03-11 09:45:43
 * Description : 盘盈盘亏记录
 */
@Service
@Slf4j
public class SurplusLossesServiceImpl implements SurplusLossesService {

    private final SurplusLossesDao surplusLossesDao;
    private final StockDao stockDao;
    private final GoodsDao goodsDao;
    private final GoodsCategoryDao goodsCategoryDao;

    @Autowired
    public SurplusLossesServiceImpl(SurplusLossesDao surplusLossesDao, StockDao stockDao, GoodsDao goodsDao, GoodsCategoryDao goodsCategoryDao) {
        this.surplusLossesDao = surplusLossesDao;
        this.stockDao = stockDao;
        this.goodsDao = goodsDao;
        this.goodsCategoryDao = goodsCategoryDao;
    }

    @Override
    public SurplusLossesDTO getById(Long id) {
        return surplusLossesDao.getById(id);
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
	public int delete(Long id) {
		log.debug("删除SurplusLosses=>{}", id);
		return surplusLossesDao.delete(id);
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
	public int update(SurplusLossesDTO surplusLossesDTO) {
        surplusLossesDTO.preUpdate();
        log.debug("修改SurplusLosses=>{}", surplusLossesDTO.getId());
        return surplusLossesDao.update(BeanConverter.map(surplusLossesDTO, SurplusLosses.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseInfo save(SurplusLossesDTO surplusLossesDTO, ResponseInfo responseInfo) {

        responseInfo.setCode(1);

        //校验
        Map<String, String> check = check(surplusLossesDTO);
        if(check != null){
            if("0".equals(check.get("code"))){
                responseInfo.setCode(0);
                responseInfo.setMessage("成功");
                surplusLossesDTO.preInsert();
                Long id = surplusLossesDao.save(BeanConverter.map(surplusLossesDTO, SurplusLosses.class));
                log.debug("新增SurplusLosses=>{}", id);
            }else{
                responseInfo.setMessage(check.get("msg"));
            }
        }
        return responseInfo;
    }

    @Override
    public PageTableResponse list(PageTableRequest request) {
        return new PageTableHandler(
                request1 -> surplusLossesDao.count(request1.getParams()),
                request2 -> surplusLossesDao.list(
                        request2.getParams(), request2.getOffset(), request2.getLimit()))
                .handle(request);
    }

    /**
     * 校验当前盘银盘亏记录是否可以保存
     * @param surplusLossesDTO
     * @return
     */
    public Map<String,String> check(SurplusLossesDTO surplusLossesDTO) {

        Map<String,String> hashMap = new HashMap();
        hashMap.put("code","0");

        Stock stock = new Stock();//库存记录
        //判断所属用户是否为空
        Long userId = surplusLossesDTO.getUserId();//用户id
        Long goodsId = surplusLossesDTO.getGoodsId();//商品id
        GoodsDTO goodsDTO = goodsDao.getById(goodsId);
        Long deptId = surplusLossesDTO.getDeptId();//部门id
        String company = surplusLossesDTO.getCompany();//公司

        if(userId != null && deptId != null){
            //查询当前用户下该商品的库存记录
            Long stockId = stockDao.getIdByUserLib(goodsId, userId, deptId);
            if(stockId != null){
                stock = stockDao.getById(stockId);
            }
        }else if(userId == null && deptId != null){
            //查询当前部门下该商品的库存记录
            Long stockId = stockDao.getIdByDeptLib(goodsId, deptId);
            if(stockId != null){
                stock = stockDao.getById(stockId);
            }
        }

        Integer totalNumber = surplusLossesDTO.getTotalNumber();
        if(totalNumber >= 0){
            if(stock != null && stock.getId() != null){
                //修改数量
                stock.setTotalNumber(stock.getTotalNumber() + totalNumber);
                stockDao.update(stock);
            }else{
                //增加
                if(totalNumber != 0){
                    //没有当前商品库存，新增一条库存信息
                    stock.preInsert();
                    stock.setGoodsId(goodsId);//商品
                    Long goodsCategoryId = goodsDTO.getCategory();
                    GoodsCategoryDTO goodsCategoryDTO =goodsCategoryDao.getById(goodsCategoryId);
                    Long parentCategory = goodsCategoryDTO.getParentId();
                    stock.setParentCategory(parentCategory);//商品类型父级
                    stock.setCategory(goodsCategoryId);//商品类型
                    stock.setUserId(userId);//所属人员
                    stock.setDeptId(deptId);//所属部门
                    stock.setCompanyId(company);//所属公司
                    stock.setTotalNumber(totalNumber);//总数量
                    stock.setIdleNumber(0);//闲置数量
                    stockDao.save(stock);
                }
            }
        }else{
            if(stock != null && stock.getId() != null){
                //当前库存记录的库存数
                Integer stockTotalNumber = stock.getTotalNumber();
                //相差数
                Integer diffNum = stockTotalNumber + totalNumber;
                if(diffNum > 0){
                    //修改库存数,保存
                    stock.setTotalNumber(diffNum);
                    stockDao.update(stock);
                }else if(diffNum == 0){
                    //删除当前库存记录
                    stockDao.delete(stock.getId());
                }else{
                    //当前库存数不足
                    hashMap.put("code","1");
                    hashMap.put("msg","当前用户或部门下此商品库存数不足!");
                }
            }else{
                hashMap.put("code","1");
                hashMap.put("msg","当前用户或部门下无此商品库存记录!");
            }
        }

        return hashMap;
    }


}
